package com.yc.atm;
import com.google.gson.Gson;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author zwei
 * @create 2024-07-19 15:10
 */
public class BankTask implements Runnable {
    private Socket socket;
    private Bank bank;
    private boolean flag;

    public BankTask(Socket socket, Bank bank) {
        this.socket = socket;
        this.bank = bank;
        this.flag= true;
    }
    @Override
    public void run() {
        try (
                //因为要用到try resource 直接关闭socket  所以socket重新在try注册
                Socket s = this.socket;
                Scanner reader = new Scanner(s.getInputStream());
                PrintWriter pw = new PrintWriter(s.getOutputStream())
        ) {
            while (flag&&!Thread.currentThread().isInterrupted()){
                //客户端是否没有传数据  如没有传  则结束
                if (!reader.hasNext()){
                    System.out.println("ATM客户端："+s.getRemoteSocketAddress()+"掉线了");
                    break;
                }
                //如果有信息  则取出
                String command=reader.next();   //next()读第一个部分  而没有读取一行
                BankAccount ba=null;
                JsonModel<BankAccount>jm=new JsonModel<>();
                //命令模式
                if ("DEPOSIT".equals(command)){
                    int id=reader.nextInt();
                    double money=reader.nextDouble();
                    ba= bank.deposite(id,money);
                }
                else if ("WITHDRAW".equals(command)){
                    int id=reader.nextInt();
                    double money=reader.nextDouble();
                    ba= bank.withdraw(id,money);
                }
                else if ("BALANCE".equals(command)){
                    int id=reader.nextInt();
                    ba=bank.search(id);
                } else if ("QUIT".equals(command)) {
                    System.out.println("ATM客户端要求主动断开。。。"+s.getRemoteSocketAddress());
                    break;
                }else {
                    jm.setCode(0);
                    jm.setErrorMsg("错误命令");
                    Gson gson=new Gson();
                    String jsonString=gson.toJson(jm);
                    pw.println(jsonString);
                    pw.flush();
                    continue;
                }
                jm.setCode(1);
                jm.setObj(ba);
                Gson gson=new Gson();
                String jsonString= gson.toJson(jm);
                pw.println(jsonString);
                pw.flush();
            }
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
